﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessLayer.Model.Services.Abstract;
using BusinessLayer.Model.Entities;
using System.Data.Linq;
using Dimebrain.TweetSharp.Fluent;
using DataAccess.Services.Abstract;

namespace DataAccess.Services
{
    public class TwitterService : ITwitterService
    {
        private readonly IntecDataContext _db = new IntecDataContext();
        private readonly Table<BusinessLayer.Model.Entities.TwitterAccount> _twitterTable;
        private readonly BusinessLayer.Model.Entities.TwitterAccount _twitterAccount;

        public TwitterService()
        {
            _twitterTable = _db.GetTable<BusinessLayer.Model.Entities.TwitterAccount>();

            GenerateAccountIfDoesntExist();

            _twitterAccount = GetAccount();           
        }

        #region ITwitterService Members

        public BusinessLayer.Model.Entities.TwitterAccount GetAccount()
        {
            return _twitterTable.First();
        }

        public void ChangePassword(string newPassword)
        {
            var account = GetAccount();

            account.Password = newPassword;
            _db.SubmitChanges();
        }

        public void ChangeAccount(string newAccount)
        {
            var account = GetAccount();

            account.Username = newAccount;
            _db.SubmitChanges();
        }

        public void PostNews(News news)
        {
            IApplicationService _appService = new ApplicationService();

            string tweetFormat = "Intecnología: \"" + news.Title + "\" " + _appService.ApplicationURL + "News.aspx";

            var request = FluentTwitter.CreateRequest()
                          .AuthenticateAs(_twitterAccount.Username, _twitterAccount.Password)
                          .Statuses().Update(tweetFormat).AsJson();

            request.Request();
        }

        #endregion

        private void GenerateAccountIfDoesntExist()
        {
            if (_twitterTable.Count() != 1)
            {
                BusinessLayer.Model.Entities.TwitterAccount twitterAccount = new BusinessLayer.Model.Entities.TwitterAccount();

                twitterAccount.Username = "pruebaintecnologia@gmail.com";
                twitterAccount.Password = "clave";

                _twitterTable.InsertOnSubmit(twitterAccount);

                _db.SubmitChanges();
            }


        }
    }
}
